package handler

import (
	"encoding/json"
	"post-admin/cache"
	"post-admin/models"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func GoodAdd(c *gin.Context) {
	good_name := c.PostForm("good_name")
	good_price := c.PostForm("good_price")
	data := models.Good{
		GoodName:  good_name,
		GoodPrice: good_price,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}
func OrderAdd(c *gin.Context) {
	order_name := c.PostForm("order_name")
	order_tel := c.PostForm("order_tel")
	gid, _ := strconv.Atoi(c.PostForm("gid"))
	data := models.Order{
		OrderName: order_name,
		OrderTel:  order_tel,
		Gid:       gid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
	})
	return
}

/*
SELECT
goods.good_name AS GoodName,
goods.good_price AS GoodPrice,
orders.order_name AS OrderName,
orders.order_tel AS OrderTel,
orders.gid AS Gid
FROM
orders
LEFT JOIN goods ON goods.id = orders.gid
*/
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var goodOrder []models.GoodOrder
	redis_key := "list_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Select(
				"goods.good_name AS GoodName",
				"goods.good_price AS GoodPrice",
				"orders.order_name AS OrderName",
				"orders.order_tel AS OrderTel",
				"orders.gid AS Gid",
			).Joins("LEFT JOIN goods ON goods.id = orders.gid").
			Offset(offset).Limit(size).Find(&goodOrder)
		jsonData, _ := json.Marshal(goodOrder)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &goodOrder)
	}
	var total int64
	models.DB.Model(models.Order{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  goodOrder,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var goodOrder models.GoodOrder
	redis_key := "list_page_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("orders").
			Select(
				"goods.good_name AS GoodName",
				"goods.good_price AS GoodPrice",
				"orders.order_name AS OrderName",
				"orders.order_tel AS OrderTel",
				"orders.gid AS Gid",
			).Joins("LEFT JOIN goods ON goods.id = orders.gid").
			Where("orders.id=?", id).Find(&goodOrder)
		jsonData, _ := json.Marshal(goodOrder)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &goodOrder)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": goodOrder,
	})
	return
}
